package cn.edu.sgu.www.pms.service.impl;

import cn.edu.sgu.www.pms.dto.UserRoleDTO;
import cn.edu.sgu.www.pms.entity.Role;
import cn.edu.sgu.www.pms.entity.UserRole;
import cn.edu.sgu.www.pms.exception.GlobalException;
import cn.edu.sgu.www.pms.mapper.RoleMapper;
import cn.edu.sgu.www.pms.mapper.UserRoleMapper;
import cn.edu.sgu.www.pms.restful.ResponseCode;
import cn.edu.sgu.www.pms.service.UserRoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 沐雨橙风ιε
 * @version 1.0
 */
@Service
public class UserRoleServiceImpl implements UserRoleService {

    private final RoleMapper roleMapper;
    private final UserRoleMapper userRoleMapper;

    @Autowired
    public UserRoleServiceImpl(RoleMapper roleMapper, UserRoleMapper userRoleMapper) {
        this.roleMapper = roleMapper;
        this.userRoleMapper = userRoleMapper;
    }

    @Override
    public void insert(UserRoleDTO userRoleDTO) {
        // 得到用户ID
        String userId = userRoleDTO.getUserId();
        // 得到角色ID
        Integer roleId = userRoleDTO.getRoleId();

        // 防止添加重复数据
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("role_id", roleId);

        Long count = userRoleMapper.selectCount(queryWrapper);

        if (count > 0) {
            throw new GlobalException(ResponseCode.FORBIDDEN, "用户已经有拥有该角色！");
        }

        UserRole userRole = new UserRole();

        userRole.setUserId(userId);
        userRole.setRoleId(roleId);

        userRoleMapper.insert(userRole);
    }

    @Override
    public void delete(UserRoleDTO userRoleDTO) {
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("role_id", userRoleDTO.getRoleId());
        queryWrapper.eq("user_id", userRoleDTO.getUserId());

        userRoleMapper.delete(queryWrapper);
    }

    @Override
    public List<Role> selectByUserId(String userId) {
        return roleMapper.selectByUserId(userId);
    }

}